<template>
  <div class="app-container">
    <div class="chart-row">
      <!-- 折线图 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <div class="chart-title">诊所收入趋势</div>
        </div>
        <div ref="lineChartRef" style="height: 400px;"></div>
      </el-card>
      
      <!-- 饼图 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <div class="chart-title">会员消费占比</div>
        </div>
        <div ref="pieChartRef" style="height: 400px;"></div>
      </el-card>
    </div>
   
    <!-- 表格部分 -->
    <div class="table-title">门诊记录</div>
    <el-table v-loading="loading" :data="guahaoList">
      <el-table-column label="挂号单号" align="center" prop="id" />
      <el-table-column label="就诊状态" align="center" prop="state">
        <template #default="scope">
          <dict-tag :options="fy_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="患者" align="center" prop="patientId">
        <template #default="scope">
          <span v-for="p in patientList" :key="p.id">
            <span v-if="scope.row.patientId == p.id">
              {{ p.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center">
        <template #default="scope">
          <span v-for="p in patientList" :key="p.id">
            <span v-if="scope.row.patientId == p.id">
              <dict-tag :options="sys_user_sex" :value="p.sex"/>
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center">
        <template #default="scope">
          <span v-for="p in patientList" :key="p.id">
            <span v-if="scope.row.patientId == p.id">
              {{ p.age }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center">
        <template #default="scope">
          <span v-for="p in patientList" :key="p.id">
            <span v-if="scope.row.patientId == p.id">
              {{ p.phone }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="接诊类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="doctor_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="科室" align="center" prop="deptId">
        <template #default="scope">
          <span v-for="d in deptList" :key="d.deptId">
            <span v-if="scope.row.deptId == d.deptId">
              {{ d.deptName }}
            </span>
          </span>
        </template>
      </el-table-column>
     
      <el-table-column label="接诊医生" align="center" prop="doctorId">
        <template #default="scope">
          <span v-for="u in userList" :key="u.userId">
            <span v-if="scope.row.doctorId == u.userId">
              {{ u.nickName }}
            </span>
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="挂号费" align="center" prop="money">
        <template #default="scope">
          <span v-for="r in registationcostList" :key="r.id">
            <span v-if="scope.row.money == r.id">
              {{ r.registrationCost }}元
            </span>
          </span>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getDailyTotalAmount } from '@/api/jy/money'
import { getVipConsumptionByGrade } from '@/api/jy/vipList'
import { listGuahao } from "@/api/chy/guahao"
import { listDept } from "@/api/system/dept"
import { listUser } from "@/api/system/user"
import { listPatient } from "@/api/chy/patient"
import { listRegistationcost } from "@/api/chy/registationcost"
import { parseTime } from '@/utils/ruoyi'
import Pagination from '@/components/Pagination/index.vue'
const { proxy } = getCurrentInstance();
const { doctor_type, fy_status } = proxy.useDict('doctor_type', 'fy_status');
const { sys_user_sex } = proxy.useDict('sys_user_sex');
// refs
const lineChartRef = ref(null)
const pieChartRef = ref(null)
let lineChart = null
let pieChart = null

// 在脚本的顶部定义一个响应式变量来存储会员消费总额
const totalVipConsumption = ref(0);

// 表格数据
const loading = ref(true)
const guahaoList = ref([])
const deptList = ref([])
const userList = ref([])
const patientList = ref([])
const registationcostList = ref([])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})
const total = ref(0)

// 初始化图表
const initCharts = () => {
  if (lineChartRef.value && pieChartRef.value) {
    lineChart = echarts.init(lineChartRef.value)
    pieChart = echarts.init(pieChartRef.value)
    initLineChart()
    initPieChart()
    window.addEventListener('resize', handleResize)
  }
}

// 获取折线图数据
const initLineChart = () => {
  getDailyTotalAmount().then(response => {
    if (response.data) {
      const recentData = response.data.slice(-7)
      const dates = recentData.map(item => item.orderDate)
      const amounts = recentData.map(item => item.dailyTotal)

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>总金额: {c} 元'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLine: {
            lineStyle: {
              color: '#E5E5E5'
            }
          },
          axisLabel: {
            formatter: value => value,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '单位（元）',
          axisLabel: {
            formatter: '{value}'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#E5E5E5'
            }
          }
        },
        series: [{
          data: amounts,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#8B95F2'
          },
          lineStyle: {
            color: '#8B95F2',
            width: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(139, 149, 242, 0.3)' },
              { offset: 1, color: 'rgba(139, 149, 242, 0.1)' }
            ])
          }
        }]
      }

      lineChart.setOption(option)
    }
  })
}

// 初始化饼图
const initPieChart = () => {
  getVipConsumptionByGrade().then(response => {
    console.log("返回的数据:", response); // 打印返回的数据
    if (response.code === 200 && Array.isArray(response.data)) {
      // 计算总额
      totalVipConsumption.value = response.data.reduce((sum, item) => sum + item.consumption, 0);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}元'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 20,
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            fontSize: 12,
            color: '#333'
          },
          formatter: name => {
            const item = response.data.find(d => `VIP ${d.vipGrade}级` === name);
            return `${name} ${item ? item.consumption : 0}元`;
          }
        },
        color: ['#909399', '#eaae55', '#7bca54', '#409eff', '#f76c6c'],
        title: {
          text: `会员消费总额: \n\n\t\t${totalVipConsumption.value} 元`, // 设置标题文本
          left: '80rpx', // 水平居中
          top: 'center', // 垂直居中
          textStyle: {
            color: '#000', // 文本颜色，根据需要调整
            fontSize: 16, // 文本大小，根据需要调整
            fontWeight: 'bold', // 文本粗细，根据需要调整
            align: 'center' // 文本居中对齐
          }
        },
        series: [{
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['35%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 4,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          data: response.data.map(item => ({
            name: `VIP ${item.vipGrade}级`,
            value: item.consumption
          }))
        }]
      };

      pieChart.setOption(option);
    } else {
      console.error("返回的数据不符合预期", response);
    }
  }).catch(error => {
    console.error("请求失败", error);
  });
};

// 获取表格数据
const getList = async () => {
  loading.value = true
  try {
    const [deptRes, userRes, patientRes, costRes, guahaoRes] = await Promise.all([
      listDept(),
      listUser(),
      listPatient(),
      listRegistationcost(),
      listGuahao()
    ])

    deptList.value = deptRes.data
    userList.value = userRes.rows
    patientList.value = patientRes.rows
    registationcostList.value = costRes.rows
    guahaoList.value = guahaoRes.rows
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 窗口大小变化处理
const handleResize = () => {
  lineChart?.resize()
  pieChart?.resize()
}

// 生命周期钩子
onMounted(() => {
  getList()
  // 使用nextTick确保DOM已经渲染
  nextTick(() => {
    initCharts()
  })
})

onBeforeUnmount(() => {
  // 清理图表实例
  if (lineChart) {
    lineChart.dispose()
    lineChart = null
  }
  if (pieChart) {
    pieChart.dispose()
    pieChart = null
  }
  // 移除事件监听器
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.chart-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  min-width: 0;
}

/* 折线图卡片占65% */
.chart-card:first-child {
  flex: 65;
}

/* 饼图卡片占35% */
.chart-card:last-child {
  flex: 35;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  color: #333;
}
</style>